package com.situ.stl.controller;

import com.situ.stl.constants.Constants;
import com.situ.stl.entity.Coach;
import com.situ.stl.entity.Member;
import com.situ.stl.service.MemberService;
import com.situ.stl.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/member")
@Slf4j
public class MemberController {
    @Autowired
    private MemberService memberService;

    @GetMapping
    public Result getAll(Integer page, Integer limit, Member member) {
        if (ObjectUtils.isEmpty(page) && ObjectUtils.isEmpty(limit)) {
            List<Member> memberList = memberService.select(member);
            return Result.success(Constants.STATUS_200, memberList);
        }
        return Result.success(Constants.STATUS_200, memberService.searchByPage(page, limit, member));
    }

    @PutMapping
    public Result modifyMember(@RequestBody Member member) {
        try {
            int row = memberService.modifyMember(member);
            if (row == 0) {
                return Result.error(Constants.EDIT_Member_ERROR, "修改会员失败");
            }else if (row == Constants.PASSWORD_ERROR){
                return Result.error(Constants.PASSWORD_ERROR,"密码错误");
            }

        } catch (Exception e) {
            log.info("修改失败");
            return Result.success(Constants.STATUS_10001, e.getMessage());
        }
        return Result.success(Constants.STATUS_200);
    }
    @DeleteMapping("/{id}")
    public Result deleteMember(@PathVariable Integer id) throws Exception {
        try {
            int row = memberService.deleteMember(id);
            if(row == 0) {
                return Result.error(Constants.STATUS_10001, "删除会员失败");
            }
        } catch (Exception e) {
            log.info("删除失败");
            return Result.success(Constants.STATUS_10001, e.getMessage());
        }
        return Result.success(Constants.STATUS_200);

    }
    @PostMapping
    public Result add(@RequestBody Member member) {

        try {
            int row = memberService.addMember(member);
            if (row == 0) {
                return Result.error(Constants.EDIT_Member_ERROR, "添加会员失败");
            }
        } catch (Exception e) {
            log.info("添加失败");
            return Result.success(Constants.STATUS_10001, e.getMessage());
        }
        return Result.success(Constants.STATUS_200);

    }

}

